package logic

import (
	"context"
	"errors"
	"manuscript-service/models/mysql"

	"manuscript-service/articlerpc/articlerpc"
	"manuscript-service/articlerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ArticleAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewArticleAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ArticleAddLogic {
	return &ArticleAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ArticleAddLogic) ArticleAdd(in *articlerpc.ArticleAddRequest) (*articlerpc.ArticleAddResponse, error) {
	// todo: add your logic here and delete this line

	var findarticle mysql.Article
	begin := mysql.DB.Begin()
	err := findarticle.FindArticle(begin, in.Title)
	if err == nil {
		begin.Rollback()
		return nil, errors.New("标题已经存在")
	}

	var style mysql.Style
	err = style.FindStyleByName(begin, in.StyleName)
	if err != nil {
		style = mysql.Style{
			Name: in.StyleName,
		}
		err = style.StyleCreate(begin)
		if err != nil {
			begin.Rollback()
			return nil, errors.New("类别创建失败")
		}
	}

	article := &mysql.Article{
		Sid:     int(style.ID),
		Title:   in.Title,
		Author:  in.Author,
		Content: in.Content,
	}
	err = article.ArticleAdd(begin)
	if err != nil {
		begin.Rollback()
		return nil, err
	}
	begin.Commit()
	return &articlerpc.ArticleAddResponse{
		ArticleId: int64(article.ID),
	}, nil
}
